package com.sky.sd.system.bean.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sky.sd.system.bean.po.Role;
import com.sky.sd.system.bean.po.User;
import com.sky.sd.system.enums.EnabledType;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/6/24 10:32
 * <br/>修改日期: 2020/6/24 10:32
 * <br/>修改列表:
 */
@Data
@ToString(callSuper = true)
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class LoginUser extends User implements UserDetails{

    // 角色集
    private List<Role> roles;

    // 权限集
    private Set<String> perms;

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<SimpleGrantedAuthority> authoritys = new HashSet<>();

        if(CollectionUtils.isNotEmpty(perms)) {
            perms.parallelStream().forEach(perm -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perm);
                authoritys.add(authority);
            });
        }

        if(CollectionUtils.isNotEmpty(roles)) {
            roles.parallelStream().forEach(role -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(StringUtils.join("ROLE_", role.getCode()));
                authoritys.add(authority);
            });
        }
        return authoritys;
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return LocalDateTime.now().isBefore(super.getPasswordValid());
    }

    @Override
    public boolean isAccountNonLocked() {
        return EnabledType.ENABLED.getValue().equals(super.getEnabled());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setEnabled(Integer enabled) {
        super.setEnabled(enabled);
    }

    public Integer getEnabled() {
        return super.getEnabled();
    }
}
